package token

import (
	"context"

	"github.com/infraboard/mcube/v2/ioc"
	"github.com/infraboard/mcube/v2/ioc/config/validator"
)

const (
	AppName = "token"
)

func GetService() Service {
	return ioc.Controller().Get(AppName).(Service)
}

// 业务域
type Service interface {
	UserService
	InnterService
}

// 1. 外部
type UserService interface {
	// 颁发令牌 登录
	IssueToken(context.Context, *IssueTokenRequest) (*Token, error)
	// 撤销令牌 退出
	RevolkToken(context.Context, *RevolkTokenRequest) (*Token, error)
}

type RevolkTokenRequest struct {
	// 访问令牌
	AccessToken string `json:"access_token"`
	// 刷新令牌, 构成一对，避免AccessToken 泄露，用户可以直接 revolk
	RefreshToken string `json:"refresh_token"`
}

func NewIssueTokenRequest(username, password string) *IssueTokenRequest {
	return &IssueTokenRequest{
		Username: username,
		Password: password,
	}
}

type IssueTokenRequest struct {
	Username string `json:"username" validate:"required"`
	Password string `json:"password" validate:"required"`
	// 记住我, Token可能1天过期, 过去时间调整为7天
	RememberMe bool `json:"remember_me"`
}

func (r *IssueTokenRequest) Validate() error {
	return validator.Validate(r)
}

// 内部
type InnterService interface {
	// 令牌校验
	ValidateToken(context.Context, *ValidateTokenRequest) (*Token, error)
}

func NewValidateTokenRequest(at string) *ValidateTokenRequest {
	return &ValidateTokenRequest{
		AccessToken: at,
	}
}

type ValidateTokenRequest struct {
	// 访问令牌
	AccessToken string `json:"access_token"`
}
